<template>
  <div class="goodsAdd">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品照片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- tab栏区域 -->
        <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeLeave" @tab-click="tabClick">
          <!-- 基本信息区域 -->
          <el-tab-pane label="基本信息" name="0">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <!-- 商品价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <!-- 商品重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item> 
            <!-- 商品数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 商品类型 -->
            <el-form-item label="商品类型" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="categoriesList" clearable
                :props="{ expandTrigger: 'hover',
                          label: 'cat_name',
                          value: 'cat_id',
                          children: 'children' }"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品参数区域 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="citem" v-for="(citem, index) in item.attr_vals" :key="index" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性区域 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form ref="formRef" label-width="100px" label-position="top">
              <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 商品图片区域 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- action 表示图片要上传到的 后台API地址 -->
            <!-- list-type是图片呈现方式 -->
            <!-- on-preview是图片预览效果 -->
            <!-- on-remove 是图片删除事件 -->
            <el-upload
              action="http://timemeetyou.com:8889/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          
          <!-- 商品内容区域 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce">

            </quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览展示对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img :src="previewPath" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getCategoriesList } from 'network/goods_category'
import { getCategoriesAttributes } from 'network/goods_params'
import { addGoods } from 'network/goods_list'

export default {
  name: 'GoodsAdd',
  data() {
    return {
      // 已进行的步骤
      activeIndex: '0',

      // 商品分类数据列表
      categoriesList: [],

      // 商品动态参数数据列表
      manyTableData: [],

      // 商品静态属性数据列表
      onlyTableData: [],

      // 图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },

      // 图片在服务端的真实地址
      previewPath: '',

      // 图片阅览对话框的展示和隐藏
      previewDialogVisible: false,

      // 添加商品的表单对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        // 商品参数
        attrs: []

      },

      // 添加商品表单的验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    // 获取商品分类数据列表
    this.getCategoriesList()
  },

  computed: {
    cateId() {
      if(this.addForm.goods_cat.length == 3)
        return this.addForm.goods_cat[2] 
    }
  },

  methods: {
    // 获取商品分类数据列表方法
    getCategoriesList() {
      getCategoriesList().then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.categoriesList = res.data
        // console.log(this.categoriesList);
      }).catch(err => this.$message.error(err))
    },

    // 商品类型级联选择器发生点击事件
    handleChange() {
      if(this.addForm.goods_cat.length !== 3 ) {
        this.addForm.goods_cat = []
      }
    },

    // 判断基本信息是否填写
    beforeLeave(activeName, oldActiveName) {
      if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.info('请完成当前页面填写')
        return false
      }
    },

    // tabs标签栏发生点击事件
    tabClick() {
      // 获取动态参数的 数据列表
      if(this.activeIndex == 1) {
        getCategoriesAttributes(this.cateId, 'many').then(res => {
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals.length == 0 ? [] : item.attr_vals.split(' ')
          })
          this.manyTableData = res.data
          // console.log(this.manyTableData);
        }).catch(err => this.$message.error(err))
      } else if(this.activeIndex == 2) {
        getCategoriesAttributes(this.cateId, 'only').then(res => {
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.onlyTableData = res.data
          console.log(this.onlyTableData);
        }).catch(err => this.$message.error(err))
      }
    },

    // 处理图片预览效果
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewDialogVisible = true
    },

    // 监听图片上传成功事件
    handleSuccess(response) {
      if(response.meta.status !== 200) return this.$message.error(response.meta.msg)
      const picInfo = { pics: response.data.tmp_path}
      this.addForm.pics.push(picInfo)
      this.$message.success(response.meta.msg)
      // console.log(this.addForm.pics);
    },

    // 处理图片删除事件 file为移除图片的信息
    handleRemove(file) {
      // 1.获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2.从 pics 数组中, 找到这个图片的索引值
      const index = this.addForm.pics.findIndex(x => x.pic === filePath)
      // 3.调用数组的 splice方法, 把图片信息对象从 pics数组 中移除
      this.addForm.pics.splice(index, 1)
    },

    // 添加 商品按钮
    addGood() {
      this.$refs.addFormRef.validate(valid => {
        if(!valid) return this.$message.error('请填写完成所有必要表单项')
        // 执行添加商品 
        // 利用深拷贝 处理分割列表
        JSON.parse(JSON.stringify(this.addForm))
        this.addForm.goods_cat = this.addForm.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性  静态属性的value值本来就是字符串
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        // 发起添加商品网络请求
        addGoods(this.addForm).then(res => {
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          console.log(res);
          
        }).catch(err => this.$message.error(err))
        this.$router.push('/home/goods')
      })
    },

  
  }
}
</script>

<style>
  .el-breadcrumb,
  .el-alert,
  .el-steps {
    margin-bottom: 30px;
  }

  .el-dialog img {
    width: 100%;
  }

  .el-button {
    margin-top: 20px;
  }
</style>